package com.yvan.es;

import com.yvan.platform.JsonWapper;
import io.searchbox.client.JestClient;
import org.slf4j.Logger;

import java.io.IOException;
import java.util.List;

public class BulkAction {

    private final Logger log;
    private String waitForActiveShards;
    private String refresh;
    private List<JsonWapper> documents;

    public BulkAction(Logger log) {
        this.log = log;
        waitForActiveShards = "";
    }

    public String getWaitForActiveShards() {
        return waitForActiveShards;
    }

    public void setWaitForActiveShards(String waitForActiveShards) {
        this.waitForActiveShards = waitForActiveShards;
    }

    public String getRefresh() {
        return refresh;
    }

    public void setRefresh(String refresh) {
        this.refresh = refresh;
    }

    public List<JsonWapper> getDocuments() {
        return documents;
    }

    public void setDocuments(List<JsonWapper> documents) {
        this.documents = documents;
    }

    public RestFulResult bulk(JestClient jestClient) throws IOException {

        String requestContent = build();
        String url = "/_bulk";
        boolean isAddParam = false;
        if (waitForActiveShards.length() > 0) {
            url += ((!isAddParam ? "?" : "&") + "wait_for_active_shards=" + getWaitForActiveShards());
            isAddParam = true;
        }
        if (refresh.length() > 0) {
            url += ((!isAddParam ? "?" : "&") + "refresh=" + getRefresh());
            isAddParam = true;
        }
        RestFulAction sq = new RestFulAction.Builder(requestContent)
                .setUrl(url)
                .setPostMethod().build();
        RestFulResult re = jestClient.execute(sq);
        return re;
    }

    private String build() throws IOException {

        if (documents == null || documents.size() < 1) {
            return null;
        }

        StringBuilder sbBulkActions = new StringBuilder();
        JsonWapper jw;
        for (JsonWapper obj : documents) {
            sbBulkActions.append(obj.toString(false));
            sbBulkActions.append('\n');
        }

        return sbBulkActions.toString();
    }
}
